package com.sgb.kjwl.view.ui.fragment.transport;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.motion.widget.MotionLayout;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.alimaplibrary.MarkerEntity;
import com.sgb.alimaplibrary.TextureMapMarkerTools;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentGoodsHallListBinding;
import com.sgb.kjwl.di.transport.DaggerTransportFragComponent;
import com.sgb.kjwl.di.transport.TransportFragModule;
import com.sgb.kjwl.model.entity.transport.CarTypeAndCarLength;
import com.sgb.kjwl.model.entity.transport.CheckStateEntity;
import com.sgb.kjwl.model.entity.transport.GoodsHallFilterEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.transport.MapSourcesEntity;
import com.sgb.kjwl.model.entity.transport.WeightAndVolumeEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.ChineseEnglishAndNumberFilter;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.LocationUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.TextViewUtils;
import com.sgb.kjwl.utils.TouchHelper;
import com.sgb.kjwl.utils.VehicleConstant;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.activity.transport.GoodsInfoJoinQuotedActivity3;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.FreightPrjDetailActivity;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.GeneralPrjDetailActivity;
import com.sgb.kjwl.view.ui.adapter.home.GoodsInfoAdapter;
import com.sgb.kjwl.view.ui.adapter.transport.CarLengthTransportAdapter3;
import com.sgb.kjwl.view.ui.adapter.transport.CarTypeTransportAdapter3;
import com.sgb.kjwl.view.ui.adapter.transport.WeightAndVolumeMinAndMaxAdapter;
import com.sgb.kjwl.view.widget.GoodsMoreFilterPopWindow;
import com.sgb.kjwl.view.widget.GoodsTypePopWindow3;
import com.sgb.kjwl.view.widget.LoadRadiusWindow;
import com.sgb.kjwl.view.widget.LoadTimePopWindow;
import com.sgb.kjwl.view.widget.MapGoodsPopWindow;
import com.sgb.kjwl.view.widget.PlaceAreaPopWindow;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.transport.GoodsListAndMapModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.recyclerview.adapter.TransportAdapterOnItemClick;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.ArrayUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.ScreenUtil;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

public class GoodsHallListFragment extends AppLazyFragment implements
        AMap.OnCameraChangeListener {

    private Context mContext;
    private static final String FLAG_FILTER = "flag_filter";
    private static final String CAN_SHOW_LISTVIEW = "canShowListView";
    private static final String PATTERN = "pattern";
    private static final String IS_SHOW_MORE_FILTER = "IS_SHOW_MORE_FILTER";
    private static final int FILTER_SELECTING = 0;
    private static final int FILTER_SELECTED = 1;
    private static final int FILTER_UNSELECTED = 2;
    //是否是图查o
    private boolean isMap = false;
    private String goodsTypeNo = DEFAULT_GOODS_TYPE;
    private String goodsSecondTypeNo = DEFAULT_GOODS_TYPE;
    private Map<String, List<CarTypeAndCarLength>> allCarTypeAndCarLengthMap = new HashMap<>();
    private ThreeLevelAreaWindow sendGoodsLocationPopWindow3;
    private ThreeLevelAreaWindow destinationPopWindow;


    private GoodsMoreFilterPopWindow goodsMorePopWindow;
    private LoadTimePopWindow loadTimePopWindow;
    private LoadRadiusWindow loadRadiusWindow;
    private PlaceAreaPopWindow placeAreaWindow;

    private int page = 1;
    private boolean isLoadMore = false;
    private int position = -1;

    //列表进行运费排序的标记：0-不按运费排序  1—升序  2-降序
    private int freightSortFlag = 0;

    private GoodsTypePopWindow3 goodsTypePopWindow;//一级分类弹窗
    private List<GoodsInfoTypeEntity3> goodsTypeData;
    private GoodsTypePopWindow3 goodsSecondTypePopWindow;//二级分类弹窗
    private List<GoodsInfoTypeEntity3> goodsSecondTypeData = new ArrayList<>();
    private Map<String, GoodsInfoTypeEntity3> allSecondTypeMap;//所有的二级分类数据map
    private List<GoodsInfoTypeEntity3> allSecondTypeData;//所有的二级分类数据
    private GoodsInfoTypeEntity3 unlimitedType;//不限的TypeBean

    //地图控制器
    private AMap aMap;
    //当前定位位置信息
    public LatLng mCurLatLng;
    private boolean isMapClick;
    //屏幕高度
    private int mScreenHeight;
    //地图缩放比例
    private float mZoom = 11;
    //最小缩放级别（全国）
    private final float mMinZoom = 3;
    private float currZoom = 11;
    List<MapSourcesEntity> bundles = new ArrayList<>();
    List<MapSourcesEntity> bundlesBus = new ArrayList<>();
    List<MarkerEntity> markerEntityList = new ArrayList<>();
    private int lastPosition;
    Bundle savedInstanceState;
    private Marker markerLast;
    //全国中心点经纬度
    private final LatLng mCenterLatLng = new LatLng(35.03349, 103.03319);
    public boolean mapShowing; //是否正在地图模式切换
    private boolean mIsNeedLoadByCamera;
    private TextureMapMarkerTools mapMarkerTools;
    private MapGoodsPopWindow mapGoodsPopWindow;
    public LatLng searchLatLng = new LatLng(LocationUtil.getCurrentLatitude(), LocationUtil.getCurrentLongitude());

    // 一级联动数据
    public List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    public List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    public List<List<List<AddressEntity>>> opt3 = new ArrayList<>();
    private int LOCATION_TYPE = -1;//0发货地，1目的地
    private boolean isFilterVisible = true;
    private boolean currentIsSearching = false;

    @Inject
    GoodsListAndMapModel listAndMapModel;
    private FragmentGoodsHallListBinding binding;
    private GoodsInfoAdapter goodsInfoAdapter;
    private int pattern = 0;
    private boolean isShowMoreFilter;
    private boolean canShowListView;
    //是否是展开的筛选栏，默认展开
    private boolean mIsExpand = true;
    //手势监听帮助类
    private TouchHelper mTouchHelper;

    public GoodsHallListFragment() {
    }


    public static GoodsHallListFragment newInstance(int pattern, boolean filterData
            , boolean isShowMoreFilter, boolean canShowListView, boolean isMap) {
        return newInstance(pattern, filterData, isShowMoreFilter, canShowListView, isMap, DEFAULT_GOODS_TYPE);
    }

    public static GoodsHallListFragment newInstance(int pattern, boolean filterData
            , boolean isShowMoreFilter, boolean canShowListView, boolean isMap, String goodsTypeNo) {
        GoodsHallListFragment fragment = new GoodsHallListFragment();
        Bundle args = new Bundle();
        args.putBoolean(FLAG_FILTER, filterData);
        args.putInt(PATTERN, pattern);
        args.putBoolean(IS_SHOW_MORE_FILTER, isShowMoreFilter);
        args.putBoolean(CAN_SHOW_LISTVIEW, canShowListView);
        args.putBoolean("is_map", isMap);
        args.putString(RouterKey.NO, goodsTypeNo);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBundleParams();
        mContext = getContext();
    }


    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerTransportFragComponent.builder()
                .appComponent(appComponent)
                .transportFragModule(new TransportFragModule(this))
                .build()
                .inject(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        this.savedInstanceState = savedInstanceState;
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_goods_hall_list, container, false);
        return binding.getRoot();
    }


    private void initData() {
        if (!isFilterVisible) {
            binding.emptyView.setVisibility(View.VISIBLE);
            binding.goodsList.setVisibility(View.GONE);
        } else {
            loadContentData();
        }

        unlimitedType = new GoodsInfoTypeEntity3();
        unlimitedType.setName("不限");
        unlimitedType.setNo(DEFAULT_GOODS_TYPE);
    }

    private void initNeedVideoParams() {
        //这种情况代表是首页加载当前fragment要添加视频数据
        if (isFilterVisible && !isShowMoreFilter) {
            listAndMapModel.filterEntity.get().setNeedVideo("1");
        } else {
            //这种情况代表是货运大厅加载当前fragment不需要添加视频数据
            listAndMapModel.filterEntity.get().setNeedVideo("0");
        }
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onClick(View v) {
//        if (ClickUtils.isDoubleClick()) {
//            return;
//        }
        switch (v.getId()) {
            //重置抽屉布局里面的筛选信息
            case R.id.reset_step:
                resetAllFilterData();
                break;
            //确定筛选
            case R.id.sure_step:
                //更新车型筛选参数
                if (!isChooseFirstDefaultItem(carTypeAdapter.getCheckDatas())) {
                    refreshLastCheckedCarType();
                    listAndMapModel.filterEntity.get().setCarType(lastCarTypeCheckedData);
                } else {
                    lastCarTypeCheckedData.clear();
                    listAndMapModel.filterEntity.get().setCarType(null);
                }
                //更新车长筛选参数
                if (!isChooseFirstDefaultItem(lengthAdapter.getCheckDatas())) {
                    refreshLastCheckedLength();
                    listAndMapModel.filterEntity.get().setLengthType(lastCarLengthCheckedData);
                } else {
                    lastCarLengthCheckedData.clear();
                    listAndMapModel.filterEntity.get().setLengthType(null);
                }
                binding.drawerLayout.closeDrawers();
                listAndMapModel.filterEntity.set(listAndMapModel.filterEntity.get());
//                setFilterBtnStatus();
                refreshData();
                break;

            //更多车长信息
            case R.id.car_length_more:
                if (null != lengthAdapter.getDatas() && lengthAdapter.getDatas().size() > 0) {
                    if (lengthAdapter.getDatas().size() < usefulCarsLengthList.size()) {
                        setCarLengthShowState(false);
                    } else {
                        setCarLengthShowState(true);
                    }
                }
                break;

            //更多车型信息
            case R.id.car_type_more:
                if (null != carTypeAdapter.getDatas() && carTypeAdapter.getDatas().size() > 0) {
                    if (carTypeAdapter.getDatas().size() < usefulCarsTypeList.size()) {
                        setCarTypeShowState(false);
                    } else {
                        setCarTypeShowState(true);
                    }
                }
                break;
            case R.id.send_goods_layout:
                LOCATION_TYPE = 0;
                if (null != addressEntityList && addressEntityList.size() > 0) {
                    showPopup(sendGoodsLocationPopWindow3, binding.llPlaceFilter);
                }
                setViewStateByState2(binding.tvSend, binding.sendGoodsIv, FILTER_SELECTING);
                break;
            case R.id.purpose_goods_layout:
                LOCATION_TYPE = 1;
                if (null != addressEntityList && addressEntityList.size() > 0) {
                    showPopup(destinationPopWindow, binding.llPlaceFilter);
                }
                setViewStateByState2(binding.tvDestination, binding.purposeGoodsIv, FILTER_SELECTING);
                break;

            case R.id.goods_more_layout:
                if (!isContainCarTypeAndCarLengthByGoodsNo(goodsTypeNo)) {
                    listAndMapModel.getCarTypeAndCarLengthList(goodsTypeNo);
                } else {
                    setCarTypeAndCarLength(allCarTypeAndCarLengthMap.get(goodsTypeNo));
                }
                break;
            case R.id.edit_view:
                binding.editView.setImageDrawable(getResources().getDrawable(R.drawable.btn_shop_up));
                showGoodsTypePopWindow();
                break;
            case R.id.tv_search_good:
                if (TextUtils.isEmpty(getSearchText())) {
                    MToast.showToast(getContext(), "请输入搜索内容");
                    return;
                }
                searchGoods(1);
                break;
            case R.id.iv_map_list:
                if (mapShowing) {
                    mapShowing = false;
                    Resources res = mContext.getResources();
                    Drawable imgs = res.getDrawable(R.drawable.ditu_blue_black);
                    imgs.setBounds(0, 0, imgs.getMinimumWidth(), imgs.getMinimumHeight());
                    binding.ivMapList.setCompoundDrawables(imgs, null, null, null);
                    binding.ivMapList.setText("图查");
                    binding.flMap.setVisibility(View.GONE);
                    binding.rlListLayout.setVisibility(View.VISIBLE);
//                    binding.tvFindCarByMapLoad.setVisibility(View.GONE);
//                    binding.flExpand.setVisibility(View.GONE);
                    listLoadData();
                } else {
                    mapShowing = true;
                    Resources res = mContext.getResources();
                    Drawable imgs = res.getDrawable(R.drawable.liebiao_black);
                    imgs.setBounds(0, 0, imgs.getMinimumWidth(), imgs.getMinimumHeight());
                    binding.ivMapList.setCompoundDrawables(imgs, null, null, null);
                    binding.ivMapList.setText("列表");
                    binding.rlListLayout.setVisibility(View.GONE);
                    binding.flMap.setVisibility(View.VISIBLE);
//                    binding.tvFindCarByMapLoad.setVisibility(View.VISIBLE);
//                    binding.flExpand.setVisibility(View.VISIBLE);
                    loadMapData();
                }

                break;

            //2.1.8.8 版本隐藏此功能
            case R.id.tv_find_car_by_map_load:
                //加载货源，手动点击时清空省市区no
//                cityByLocation(searchLatLng.latitude, searchLatLng.longitude);
//                resetSearchContent();
//                refreshData();
                break;

            case R.id.load_time_layout:
                showPopup(loadTimePopWindow, binding.selectLayout);
                binding.flExpand.setVisibility(View.GONE);
                setViewStateByState(binding.loadTime, binding.loadTimeIv, binding.loadTimeLayout, FILTER_SELECTING);
                break;
            case R.id.join_price:
                GoodsInfoJoinQuotedActivity3.start(getActivity());
                break;
            case R.id.message_num_layout:
                //消息
                // messagePopWindow.showPopwindowRight(binding.messageNumLayout);
                break;

            //2.1.8.8 新增筛选类型
            case R.id.goods_classification_layout://货源分类（一级分类）
                showGoodsTypePopWindow();
                break;

            case R.id.source_type_layout://货源类型（二级分类）
                binding.flExpand.setVisibility(View.GONE);
                showGoodsSecondTypePopWindow();
                break;

            case R.id.loading_radius_layout://装货半径
                showPopup(loadRadiusWindow, binding.llPlaceFilter);
                binding.flExpand.setVisibility(View.GONE);
                setViewStateByState2(binding.tvLoadingRadius, binding.loadingRadiusIv, FILTER_SELECTING);
                break;

            case R.id.destination_area_layout:
                if (listAndMapModel.purposeLocation.get()==null||TextUtils.isEmpty(listAndMapModel.purposeLocation.get().getProvinceNo())){
                    MToast.showToast(mContext,"请先选择目的地");
                    return;
                }
                showPopup(placeAreaWindow,binding.llPlaceFilter);
                setViewStateByState2(binding.tvDestinationArea, binding.destinationAreaIv, FILTER_SELECTING);
                break;

            case R.id.freight_sort_layout://运费排名
                handlerFreightSort(true);
                break;
        }
    }

    /**
     * 处理运费排序点击事件
     *
     * @param isRefreshData 是否刷新页面数据
     */
    private void handlerFreightSort(boolean isRefreshData) {
        switch (freightSortFlag) {
            case 2:
                freightSortFlag = 1;
                binding.freightSortUpIv.setImageResource(R.mipmap.ic_up_arrow);
                binding.freightSortDownIv.setImageResource(R.mipmap.ic_down_arrow_n);
                binding.tvFreightSort.setTextColor(getResources().getColor(R.color.color_main));
                binding.freightSortLayout.setBackgroundResource(R.drawable.shape_theme_coner);
                break;

            case 0:
                if (!isRefreshData) {
                    binding.freightSortUpIv.setImageResource(R.mipmap.ic_up_arrow_n);
                    binding.freightSortDownIv.setImageResource(R.mipmap.ic_down_arrow_n);
                    binding.tvFreightSort.setTextColor(getResources().getColor(R.color.color_tab_one));
                    binding.freightSortLayout.setBackgroundResource(R.drawable.circle_gray_bkg);
                } else {
                    freightSortFlag = 2;
                    binding.freightSortUpIv.setImageResource(R.mipmap.ic_up_arrow_n);
                    binding.freightSortDownIv.setImageResource(R.mipmap.ic_down_arrow);
                    binding.tvFreightSort.setTextColor(getResources().getColor(R.color.color_main));
                    binding.freightSortLayout.setBackgroundResource(R.drawable.shape_theme_coner);
                }
                break;
            case 1:
                freightSortFlag = 2;
                binding.freightSortUpIv.setImageResource(R.mipmap.ic_up_arrow_n);
                binding.freightSortDownIv.setImageResource(R.mipmap.ic_down_arrow);
                binding.tvFreightSort.setTextColor(getResources().getColor(R.color.color_main));
                binding.freightSortLayout.setBackgroundResource(R.drawable.shape_theme_coner);
                break;
        }
        listAndMapModel.filterEntity.get().setFreightSort(freightSortFlag);
        if (isRefreshData) {
            refreshData();
        }
    }

    private void listLoadData() {
        if (currentIsSearching) {
            searchGoods(1);
        } else {
            refreshData();
        }
    }

    private void searchGoods(int page) {
        if (TextUtils.isEmpty(getSearchText())) {
            binding.goodsListRefreshLayout.finishRefresh();
            binding.goodsListRefreshLayout.finishLoadMore();
            return;
        }
        currentIsSearching = true;
        this.page = page;
        resetFilterData();
        if (mapShowing) {
            listAndMapModel.getMapList(pattern, getSearchText());
        } else {
            searchGoodsList();
        }
    }

    private String getSearchText() {
        return binding.etView.getText().toString();
    }

    private void searchGoodsList() {
        listAndMapModel.getSourceList(page, pattern, getSearchText());
    }

    //获取当前缩放比例下的地图半径
    public void getCurrentRadius() {
        if (mScreenHeight == 0) {
            mScreenHeight = ScreenUtil.getDisplayHeight();
        }
        //屏幕高度的一半 * 当前缩放1px代表的米数
        listAndMapModel.radius = NumberUtil.trim0(mScreenHeight / 2f * aMap.getScalePerPixel());
    }

    /**
     * 通过经纬度获取位置信息
     *
     * @param lat
     * @param lon
     */
    public void cityByLocation(double lat, double lon) {
        GeocodeSearch geocodeSearch = new GeocodeSearch(getActivity());
        // 第一个参数表示一个LatLng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(lat,
                lon), 200, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(query);
        //搜索位置信息
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int code) {
                if (code != 1000) return;
                RegeocodeAddress address = result.getRegeocodeAddress();
                if (address != null) {
                    refreshSendCitySelect(address.getProvince(), address.getCity(), address.getDistrict());
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult result, int code) {

            }
        });
    }

    //地图移动时刷新发货地文字
    private void refreshSendCitySelect(String province, String city, String district) {
        sendGoodsLocationPopWindow3.setDataAndPosition(addressEntityList, province, city, district);
        BaseAreaEntity[] entities = sendGoodsLocationPopWindow3.findCode(province, city, district);
        binding.tvSend.setText(entities[1].getSimpleName());
    }

    private void initMap(Bundle savedInstanceState) {
        mapGoodsPopWindow = new MapGoodsPopWindow(getActivity());
        mapGoodsPopWindow.setOnDismissListener(() -> {
            isMapClick = false;
            MapSourcesEntity entity = bundles.get(lastPosition);
            if (markerLast != null) {
                markerLast.setIcon(BitmapDescriptorFactory.fromView(getMarkerView(entity, false)));
            }

        });
        mapGoodsPopWindow.setOnClickCallBack(account -> {
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                VerificationCodeLoginActivity.start(getActivity());
            } else {
                // TODO IM功能目前需要全部去掉，此处需要后期IM迁移完成后完善
                buildSingleTalking(account);
            }
        });
        mapMarkerTools = new TextureMapMarkerTools(getActivity(), getLifecycle(), false);
        mapMarkerTools.init(savedInstanceState, binding.mapFindGoodsByMap);
        aMap = binding.mapFindGoodsByMap.getMap();
        aMap.setOnCameraChangeListener(this);//拖动监听
        aMap.setOnMarkerClickListener(marker -> {
            isMapClick = true;
            if (marker.getObject() != null) {
                MapSourcesEntity goods = (MapSourcesEntity) marker.getObject();
                for (int i = 0; i < bundles.size(); i++) {
                    if (goods.getNo().equals(bundles.get(i).getNo())) {
                        setMarkStyle(i, marker, true);
                        resetMarker(marker.getId(), marker, lastPosition);
                        markerLast = marker;
                        lastPosition = i;
                        isMapClick = true;
                        showMarkerView(i);
                    }
                }

            }
            return false;
        });
        //todo 手势监听
        aMap.setOnMapTouchListener(motionEvent -> {
            if (mTouchHelper == null) {
                mTouchHelper = TouchHelper.newInstance().addTouchListener(new TouchHelper.TouchListenerProxy() {
                    @Override
                    public void handlerUpTouch(float downX, float downY, float upX, float upY) {
                        //纵向滑动距离小于-100px
                        if (mIsExpand && upY - downY < -100) {
                            binding.mlFilterRoot.transitionToEnd();
                        }
                    }
                });
            }
            mTouchHelper.onTouch(null, motionEvent);
        });
    }

    private void loadMapData() {
        if ("全国".equals(binding.tvSend.getText().toString())) {
            //地图缩小展示全中国
            mZoom = mMinZoom;
            mIsNeedLoadByCamera = true;
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCenterLatLng, mZoom));
            if (currentIsSearching) {
                searchGoods(1);
            } else {
                refreshData();
            }

        } else {
            //查找经纬度刷新地图
            listAndMapModel.getLocation(getActivity(), listAndMapModel.sendLocation.get().getProvinceName(), DefaultUtil.getString(listAndMapModel.sendLocation.get().getCityName()));
        }
    }

    private void addMarker(List<MapSourcesEntity> list, String title) {
        markerEntityList.clear();
        for (MapSourcesEntity entity : list) {
            List<String> location = entity.getLocation();
            if (location != null && null != list && list.size() > 0 && !TextUtils.isEmpty(location.get(1)) && !TextUtils.isEmpty(location.get(0))) {
                LatLng latLng = new LatLng(Double.valueOf(location.get(1)), Double.valueOf(location.get(0)));
                MarkerEntity markerEntity;
                markerEntity = new MarkerEntity(latLng, getMarkerView(entity, false), entity.getNo());
                bundles.add(entity);
                markerEntityList.add(markerEntity);
            }
        }
        for (int i = 0; i < markerEntityList.size(); i++) {
            Marker marker = aMap.addMarker(mapMarkerTools.getMarkerOptions(markerEntityList.get(i)));
            marker.setObject(bundles.get(i));
        }
    }

    private View getMarkerView(MapSourcesEntity entity, boolean isBigMarkView) {
        View markerView = LayoutInflater.from(getActivity()).inflate(R.layout.view_marker_goods_source, null);
        TextView freight = markerView.findViewById(R.id.tv_marker_freight);
        TextView destination = markerView.findViewById(R.id.tv_marker_destination);
        if (entity.getFreightType() != 0) {
            freight.setText("电议");
        } else {
            freight.setText(String.format("%s元%s", NumberUtil.trim0(entity.getFreight()), entity.getFreightUnitWords()));
        }
        String des = entity.getDestCityName() + entity.getDestDistrictName();
        if (des.length() > 5) {
            destination.setText(des.substring(0, 4) + "...");
        } else {
            destination.setText(des);
        }
        if (entity.getPattern() == 1) {
            if (isBigMarkView) {
                markerView.setBackgroundResource(R.mipmap.bg_goods_marker_select);
            } else {
                markerView.setBackgroundResource(R.mipmap.bg_goods_marker_normal);
            }
        } else {
            if (isBigMarkView) {
                markerView.setBackgroundResource(R.mipmap.bg_bidding_marker_select);
            }else {
                markerView.setBackgroundResource(R.mipmap.bg_bidding_marker_normal);
            }
        }
        return markerView;
    }

    //设置maker大小图标
    private void setMarkStyle(int pos, Marker marker, boolean isBigMarkView) {
        MapSourcesEntity entity = bundles.get(pos);
        BitmapDescriptor bitmapSmall = null;
        bitmapSmall = BitmapDescriptorFactory.fromView(getMarkerView(entity, isBigMarkView));
        marker.setIcon(bitmapSmall);
    }

    private void resetMarker(String curMarkerId, Marker markerNew, int pos) {
        MapSourcesEntity entity = bundles.get(pos);
        if (null != markerLast) {
            if (!TextUtils.equals(curMarkerId, markerLast.getId())) {
                markerLast.setIcon(BitmapDescriptorFactory.fromView(getMarkerView(entity, false)));
            }
        }
    }

    public void showMarkerView(int pos) {
        MapSourcesEntity entity;
        entity = bundles.get(pos);
        mapGoodsPopWindow.showPopwindowBottom(binding.mapFindGoodsByMap);
        mapGoodsPopWindow.setData(entity);
    }

    private void listLoadMoreData() {
        page = page + 1;
        isLoadMore = true;
        if (currentIsSearching) {
            if (mapShowing) {
                return;
            }
            searchGoods(page);
        } else {
            listAndMapModel.getSourceList(page, pattern, "");
        }
    }


    private void refreshData() {
        //只要是刷新数据都认为不是在进行搜索
        currentIsSearching = false;
        page = 1;
        isLoadMore = false;
        if (mapShowing) {
            listAndMapModel.getMapList(pattern, "");
        } else {
            listAndMapModel.getSourceList(page, pattern, "");
        }
    }


    private void initViews() {
        binding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);//禁止抽屉侧滑出来
        binding.goodsList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull @NotNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("scrollLen", "" + dy);
                if (mIsExpand && dy > 30) {//向上滑动
                    binding.mlFilterRoot.transitionToEnd();
                }
            }
        });

        initWeightRecyclerView();
        initVolumeRecyclerView();
        initCarTypeView();
        initCarLengthView();
        initFilterView();
        initListView();
        initSendGoodsLocationPopWindow();
        initDestinationPopWindow();
        initTypePopWindow();
        initLoadTimePopWindow();
        initLoadRadiusPopWindow();
        initPlaceAreaPopWindow();
        initClickEvent();
        initMap(savedInstanceState);

        binding.etView.setFilters(new InputFilter[]{new ChineseEnglishAndNumberFilter()});
    }

    private void initClickEvent() {
        binding.setOnClick(this::onClick);
        //todo 筛选栏动画监听
        binding.mlFilterRoot.setTransitionListener(new MotionLayout.TransitionListener() {
            @Override
            public void onTransitionStarted(MotionLayout motionLayout, int i, int i1) {

            }

            @Override
            public void onTransitionChange(MotionLayout motionLayout, int i, int i1, float v) {

            }

            @Override
            public void onTransitionCompleted(MotionLayout motionLayout, int i) {
                mIsExpand = binding.mlFilterRoot.getProgress() == 0.0f;
                if (mIsExpand) {
                    binding.tvExpand.setText("收起筛选条件");
                    TextViewUtils.changeTextView(getActivity(), binding.tvExpand, R.drawable.btn_shop_up, false);
                } else {
                    binding.tvExpand.setText("更多筛选条件");
                    TextViewUtils.changeTextView(getActivity(), binding.tvExpand, R.drawable.btn_shop_down, false);
                }
            }

            @Override
            public void onTransitionTrigger(MotionLayout motionLayout, int i, boolean b, float v) {
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        listAndMapModel.isMap = !canShowListView;
        initViews();
        initNeedVideoParams();
        initData();
    }


    /**
     * 根据经纬度移动地图，标记中心点
     */
    private void cameraToPosition(Double lat, Double lng) {
        if (lat == 0 || lng == 0) return;
        //标记不是用户滑动
        mIsNeedLoadByCamera = true;
        //切换地图中心点
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), mZoom));
    }

    public void refreshGoodsByLatLng(LatLng latLng) {
        if (latLng != null) {
            mZoom = 11;
            searchLatLng = latLng;
            if (mapShowing) {
                cameraToPosition(latLng.latitude, latLng.longitude);
            }
            refreshData();
        }
    }

    public void loadContentData() {
        //只有展示筛选功能，才拉取筛选数据
        if (isFilterVisible) {
            if (!isInitAddressData()) {
                listAndMapModel.getAddressModel();
            }
            if (!isInitGoodsTypeData()) {
                listAndMapModel.getGoodsTypeData();
            }
        } else {
            initLocationData();
        }
    }

    /**
     * 初始化位置信息
     */
    private void initLocationData() {
        //在图查里面只展示地图状态时直接拉取当前地图的相关货源信息
        if ("全国".equals(binding.tvSend.getText().toString())) {
            //地图缩小展示全中国
            mZoom = mMinZoom;
            mIsNeedLoadByCamera = true;
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCenterLatLng, mZoom));
            if (currentIsSearching) {
                searchGoods(1);
            } else {
                refreshData();
            }
        } else {
            //查找经纬度刷新地图
            if (LocationUtil.isOpenLocation(getContext())) {
                String provinceName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.Province, "新疆");
                String cityName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.City, "乌鲁木齐");
                String areaName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.Area, "天山");
                //查找设置省市no
                findAddressCode(provinceName, cityName);
                //获取定位数据
                listAndMapModel.getLocation(getActivity(), provinceName, cityName);
                listAndMapModel.sendLocation.get().setProvinceName(provinceName);
                listAndMapModel.sendLocation.get().setCityName(cityName);
                listAndMapModel.sendLocation.get().setAreaName(areaName);
            } else {
                //查找设置省市no
                findAddressCode("新疆", "乌鲁木齐");
                //获取定位数据
                listAndMapModel.getLocation(getActivity(), "新疆", "乌鲁木齐");
                listAndMapModel.sendLocation.get().setProvinceName("新疆");
                listAndMapModel.sendLocation.get().setCityName("乌鲁木齐");
                listAndMapModel.sendLocation.get().setAreaName("天山");
            }
        }
    }

    private void findAddressCode(String provinceName, String cityName) {
        AddressEntity[] code = AddressHelper.getInstance().findCode(provinceName, cityName, "");
        if (code != null && code.length >= 3) {
            //设置省市区简称no
            if (code[0] != null) {
                listAndMapModel.sendLocation.get().setProvinceNo(code[0].getNo());
                listAndMapModel.sendLocation.get().setProvinceName(code[0].getSimpleName());
            }
            if (code[1] != null) {
                listAndMapModel.sendLocation.get().setCityNo(code[1].getNo());
                listAndMapModel.sendLocation.get().setCityName(code[1].getSimpleName());
            }
        }
    }

    private boolean isInitAddressData() {
        return null != addressEntityList && addressEntityList.size() > 0;
    }

    private boolean isInitGoodsTypeData() {
        return null != goodsTypeData && goodsTypeData.size() > 0;
    }


    //加载货物列表
    public void refreshGoodsInfoList(List<GoodsInfoEntity> list, boolean isMore) {
        if (goodsInfoAdapter == null) {
            return;
        }
        if (isLoadMore) {
            binding.goodsListRefreshLayout.finishLoadMore();
            if (list.size() > 0) {
                goodsInfoAdapter.addData(list);
            } else {
                binding.goodsListRefreshLayout.finishLoadMoreWithNoMoreData();
            }
            binding.goodsList.setVisibility(View.VISIBLE);
        } else {
            binding.goodsListRefreshLayout.finishRefresh();
            if (list.size() > 0) {
                binding.goodsList.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                goodsInfoAdapter.setDatas(list);
                if (list.size() < 10) {
                    binding.goodsListRefreshLayout.finishLoadMoreWithNoMoreData();
                }
            } else {
                goodsInfoAdapter.setDatas(null);
                binding.goodsList.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
        binding.goodsListRefreshLayout.setNoMoreData(isMore);
    }

    /**
     * 获取货物类型后更新数据
     *
     * @param list
     */
    public void refreshGoodsTypeData(List<GoodsInfoTypeEntity3> list) {
        if (ArrayUtil.isNullOrEmpty(list)) {
            MToast.showToast(mContext, "数据未加载");
            return;
        }
        goodsTypeData = list;
        if (!TextUtils.isEmpty(goodsTypeNo) && !goodsTypeNo.equals(DEFAULT_GOODS_TYPE)) {
            for (int i = 0; i < list.size(); i++) {
                GoodsInfoTypeEntity3 entity = list.get(i);
                if (goodsTypeNo.equals(entity.getNo())) {
                    listAndMapModel.goodsType.set(entity);
                    binding.tvGoodsClassification.setText(entity.getName());
                    setViewStateByState(binding.tvGoodsClassification, binding.goodsClassificationIv, binding.goodsClassificationLayout, FILTER_SELECTED);
                }
            }
        }
        /*组装所有的二级分类数据信息*/
        combinationAllSecondType(list);

        initLocationData();

        ///*********2.1.8.8 去掉头部分类 tabLayout
//        int index = 0;
//        for (int i = 0; i < list.size(); i++) {
//            GoodsInfoTypeEntity3 entity3 = list.get(i);
//            binding.tablayout.addTab(binding.tablayout.newTab().setText(entity3.getName()));
//            if (!TextUtils.isEmpty(goodsTypeNo) && goodsTypeNo.equals(entity3.getNo())) {
//                index = i;
//            }
//        }
//        int finalIndex = index;
//        initTabLayout();
//        binding.tablayout.postDelayed(() -> {
//            binding.tablayout.selectTab(binding.tablayout.getTabAt(finalIndex));
//            //开始定位并刷新数据
//            initLocationData();
//        }, 100);
    }

    /**
     * 组装所有的二级分类数据信息
     *
     * @param list
     */
    private void combinationAllSecondType(List<GoodsInfoTypeEntity3> list) {
        if (list == null)
            return;
        if (allSecondTypeMap == null)
            allSecondTypeMap = new HashMap<>();
        else
            allSecondTypeMap.clear();

        for (GoodsInfoTypeEntity3 goodsInfoTypeEntity : list) {
            if (goodsInfoTypeEntity.getChildList() != null && goodsInfoTypeEntity.getChildList().size() > 0) {
                for (GoodsInfoTypeEntity3 typeEntity : goodsInfoTypeEntity.getChildList()) {
                    if (!TextUtils.isEmpty(typeEntity.getNo())) {
                        if (!allSecondTypeMap.keySet().contains(typeEntity.getNo()))
                            allSecondTypeMap.put(typeEntity.getNo(), typeEntity);
                    }
                }
            }
        }
        allSecondTypeData = new ArrayList<>();
        for (GoodsInfoTypeEntity3 value : allSecondTypeMap.values()) {
            allSecondTypeData.add(value);
        }
    }

    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        addressEntityList = datas;
        initProvinceCityAreaData();
//        destinationPopWindow.setData(addressEntityList, true);
    }

    /**
     * 一级分类弹窗
     */
    private void showGoodsTypePopWindow() {
        if (goodsTypeData == null || goodsTypeData.size() == 0) {
            listAndMapModel.getGoodsTypeData();
        } else {
            goodsTypePopWindow.showPopwindow(binding.selectLayout, 0, 0);
            goodsTypePopWindow.setData(goodsTypeData, position);
            goodsTypePopWindow.setSelectTypeNo(goodsTypeNo);
            setViewStateByState(binding.tvGoodsClassification, binding.goodsClassificationIv, binding.goodsClassificationLayout, FILTER_SELECTING);
        }
    }

    /**
     * 二级分类弹窗
     */
    private void showGoodsSecondTypePopWindow() {
        if (goodsSecondTypeData.size() > 0) {
            goodsSecondTypePopWindow.showPopwindow(binding.selectLayout, 0, 0);
            goodsSecondTypePopWindow.setData(goodsSecondTypeData, -1);
            goodsSecondTypePopWindow.setSelectTypeNo(goodsSecondTypeNo);
            setViewStateByState(binding.tvSourceType, binding.sourceTypeIv, binding.sourceTypeLayout, FILTER_SELECTING);
        } else {
            List<GoodsInfoTypeEntity3> entity3s = getSecondByFirstType();
            if (entity3s != null) {
                //添加一个不限
                goodsSecondTypeData.clear();
                goodsSecondTypeData.add(unlimitedType);
                if (entity3s.size() > 0) {
                    goodsSecondTypeData.addAll(entity3s);
                }
                goodsSecondTypePopWindow.setData(goodsSecondTypeData, -1);
            }
        }
    }

    /**
     * 根据一级货物类型查找二级货物类型
     */
    private List<GoodsInfoTypeEntity3> getSecondByFirstType() {
        if (goodsTypeData == null || goodsTypeData.size() == 0 || TextUtils.isEmpty(goodsTypeNo)) {
            MToast.showToast(mContext, "请先选择货源分类");
            return null;
        }
        if (goodsTypeData != null && goodsTypeData.size() > 0) {
            for (GoodsInfoTypeEntity3 typeData : goodsTypeData) {
                if (typeData.getNo().equals(goodsTypeNo)) {
                    return typeData.getChildList();
                }
            }
        }
        return new ArrayList<>();
    }

    /**
     * 展示选择弹窗
     */
    public void showPopup(BasePopWindow pop, View view) {
        if (pop==null)
            return;
        if (getActivity() instanceof MainActivity) {
            EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_LOGISTICS_WINDOW_TOP));
            new Handler().postDelayed(() -> pop.showPopwindow(view, 0, 0), 300);
        } else {
            pop.showPopwindow(view, 0, 0);
        }
    }


    private void initProvinceCityAreaData() {
        //查找地址下标
        String provinceName = "", cityName = "", areaName = "不限";
        if (LocationUtil.isOpenLocation(getContext())) {
            provinceName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.Province, "新疆");
            cityName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.City, "乌鲁木齐");
        } else {
            provinceName = "新疆";
            cityName = "乌鲁木齐";
        }
        sendGoodsLocationPopWindow3.setDataAndPosition(addressEntityList, provinceName, cityName, areaName);
        sendGoodsLocationPopWindow3.setShowOnlyAreaNoData(true);
        destinationPopWindow.setDataAndPosition(addressEntityList, "", "", "");
        destinationPopWindow.setShowOnlyAreaNoData(true);
        if (cityName.endsWith("市")) {
            //针对直辖市处理(适应接口)
            cityName = cityName.substring(0, cityName.length() - 1);
        }
        binding.tvSend.setText(cityName);
        setViewStateByState2(binding.tvSend, binding.sendGoodsIv, FILTER_SELECTED);
    }


    private void refreshListView() {
        refreshData();
    }

    public boolean isContainCarTypeAndCarLengthByGoodsNo(String goodsNo) {
        if (TextUtils.isEmpty(goodsNo))
            goodsNo = DEFAULT_GOODS_TYPE;
        boolean isHave = allCarTypeAndCarLengthMap.keySet().contains(goodsNo);
        return isHave;
    }

    public void finishRefreshOrLoadMore() {
        if (isLoadMore) {
            binding.goodsListRefreshLayout.finishLoadMore();
        } else {
            binding.goodsListRefreshLayout.finishRefresh();
        }
    }

    public void showMapList(List<MapSourcesEntity> datas) {
        if (mapMarkerTools == null) {
            return;
        }
        mapMarkerTools.mapClear();
        lastPosition = 0;
        try {
            if (null != datas && datas.size() > 0) {
                bundles.clear();
                addMarker(datas, "");
            } else {
                MToast.showLongToast(getActivity(), "没有更多货源了");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCameraChangeFinish(CameraPosition position) {
        searchLatLng = position.target;
        getCurrentRadius();
        if (isMapClick) {
            //图标点击时不做请求
            return;
        }
        if (currZoom != position.zoom) {
            //地图缩放，不做数据搜索操作
            currZoom = position.zoom;
            return;
        } else {
            //移动位置 同步改变发货地
            cityByLocation(position.target.latitude, position.target.longitude);
            // TODO: 2021/12/9 重新拉取数据
//            switchMapAndListLoadData();
//        if (mIsNeedLoadByCamera) {
//            mIsNeedLoadByCamera = false;}
        }

    }

    private void switchMapAndListLoadData() {
        if (currentIsSearching) {
            searchGoods(1);
        } else {
            refreshData();
        }
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
    }


    private void initBundleParams() {
        if (getArguments() != null) {
            isFilterVisible = getArguments().getBoolean(FLAG_FILTER, true);
            isShowMoreFilter = getArguments().getBoolean(IS_SHOW_MORE_FILTER, false);
            canShowListView = getArguments().getBoolean(CAN_SHOW_LISTVIEW, true);
            isMap = getArguments().getBoolean("is_map", false);
            pattern = getArguments().getInt(PATTERN, 1);
            goodsTypeNo = getArguments().getString(RouterKey.NO, DEFAULT_GOODS_TYPE);
            mapShowing = isMap;
        }
    }

    private void initFilterView() {
        binding.selectLayout.setVisibility(isFilterVisible ? View.VISIBLE : View.GONE);
        binding.loadTimeLayout.setVisibility(isFilterVisible ? View.VISIBLE : View.GONE);
        binding.goodsMoreLayout.setVisibility(isFilterVisible && isShowMoreFilter ? View.VISIBLE : View.INVISIBLE);
        binding.mapListviewSwitch.setVisibility(canShowListView ? View.VISIBLE : View.GONE);
        binding.rlListLayout.setVisibility(canShowListView ? View.VISIBLE : View.GONE);
        binding.flMap.setVisibility(canShowListView ? View.GONE : View.VISIBLE);
//        binding.tvFindCarByMapLoad.setVisibility(canShowListView ? View.GONE : View.VISIBLE);
//        binding.flExpand.setVisibility(mapShowing ? View.VISIBLE : View.GONE);
    }

    private void initListView() {
        if (goodsInfoAdapter == null) {
            goodsInfoAdapter = new GoodsInfoAdapter(getActivity(), new ArrayList<>());
            if(pattern==0){
                goodsInfoAdapter.setPageName("1");
            }else{
                goodsInfoAdapter.setPageName("2");
            }
        }
        binding.goodsListRefreshLayout.setEnableLoadMore(true);
        binding.goodsListRefreshLayout.setEnableRefresh(true);
        binding.goodsList.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        binding.goodsList.setAdapter(goodsInfoAdapter);
        goodsInfoAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (goodsInfoAdapter.isMultipleClick()) {
                return;
            }
            if (null != goodsInfoAdapter && goodsInfoAdapter.getData().size() > 0) {
                listAndMapModel.goodsSourceStatusCheck(goodsInfoAdapter.getData().get(position).getNo(), position);
            }
        });
        binding.goodsListRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                listLoadMoreData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (currentIsSearching) {
                    searchGoods(1);
                } else {
                    refreshData();
                }

            }
        });
    }

    private void initSendGoodsLocationPopWindow() {
        //发货省份popWindow
        sendGoodsLocationPopWindow3 = new ThreeLevelAreaWindow(getActivity()) {
            @Override
            protected void resultContent(String name, String simpleName) {
                binding.tvSend.setText(simpleName);
            }
        };
        sendGoodsLocationPopWindow3.setBgView(binding.grayLayout);
        sendGoodsLocationPopWindow3.setAreaSingle();
        sendGoodsLocationPopWindow3.setCitySingle();
        sendGoodsLocationPopWindow3.setProvinceSingle();
        sendGoodsLocationPopWindow3.setShowSimpleName(true);
        sendGoodsLocationPopWindow3.setAllSingleSelect(true);
        sendGoodsLocationPopWindow3.setOnlyShowProAndCity(true);
        sendGoodsLocationPopWindow3.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                //当选择了发货地后搜索内容要清空
                resetSearchContent();
                listAndMapModel.sendLocation.set(entity);
                //不是地图模式的时候直接去拉数据       --2.1.9 列表模式也需要去获取发货地的经纬度（请求接口需要传参）
//                if (!mapShowing) {
//                    refreshData();
//                    return;
//                }
                //地图模式的时候去操作地图变化再去拉去相关数据
                if ("不限".equals(entity.getProvinceName())) {
                    if (mapShowing) {
                        //地图缩小展示全中国
                        mZoom = mMinZoom;
                        mIsNeedLoadByCamera = true;
                        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCenterLatLng, mZoom));
                    } else {
                        refreshData();
                    }
                } else {
                    //查找经纬度刷新地图
                    listAndMapModel.getLocation(getActivity(), listAndMapModel.sendLocation.get().getProvinceName(), DefaultUtil.getString(listAndMapModel.sendLocation.get().getCityName()));
                }
            }
        });
        sendGoodsLocationPopWindow3.setOnDismissListener(() -> {
            setViewStateByState2(binding.tvSend, binding.sendGoodsIv, FILTER_SELECTED);
        });
    }

    private void initDestinationPopWindow() {
        //收货省份popWindow
        destinationPopWindow = new ThreeLevelAreaWindow(getActivity()) {
            @Override
            protected void resultContent(String name, String simpleName) {
                binding.tvDestination.setText(simpleName);
            }
        };
        destinationPopWindow.setBgView(binding.grayLayout);
        destinationPopWindow.setAreaSingle();
        destinationPopWindow.setCitySingle();
        destinationPopWindow.setProvinceSingle();
        destinationPopWindow.setShowSimpleName(true);
        destinationPopWindow.setAllSingleSelect(true);
        destinationPopWindow.setOnlyShowProAndCity(true);
        destinationPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object proId, Object cityId, Object areaId) {
                //当选择了目的地后搜索内容要清空
                resetSearchContent();
                BaseAreaEntity pro = (BaseAreaEntity) proId;
                BaseAreaEntity city = (BaseAreaEntity) cityId;
                BaseAreaEntity area = (BaseAreaEntity) areaId;
                GoodsSourceLocationEntity entity = new GoodsSourceLocationEntity();

                entity.setProvinceNo(pro.getNo());
                entity.setCityNo(city.getNo());
                if (area != null) {
                    entity.setAreaNo(area.getNo());
                }
                binding.tvDestination.setText(entity.getSimpleName());
                listAndMapModel.purposeLocation.set(entity);
                refreshData();
            }
        });
        destinationPopWindow.setOnDismissListener(() -> {
            boolean unSetDestAddress = "目的地".equals(binding.tvDestination.getText());
            if (unSetDestAddress) {
                setViewStateByState2(binding.tvDestination, binding.purposeGoodsIv, FILTER_UNSELECTED);
            } else {
                setViewStateByState2(binding.tvDestination, binding.purposeGoodsIv, FILTER_SELECTED);
            }
        });
    }

    private void initgoodsMorePopWindow() {
        //更多
        if (isMap) {
            goodsMorePopWindow = new GoodsMoreFilterPopWindow(getActivity(), 2, true);
        } else {
            goodsMorePopWindow = new GoodsMoreFilterPopWindow(getActivity(), 3, true);
        }
        goodsMorePopWindow.setBgView(binding.bgPopGrayLayout);
        goodsMorePopWindow.setOnDismissListener(() -> binding.goodsMoreIv.setSelected(false));
        goodsMorePopWindow.setOnResultCallBack(result -> {
            //当选择了更多里面的筛选条件后搜索内容要清空
            resetSearchContent();
            GoodsHallFilterEntity filterEntity = (GoodsHallFilterEntity) result;
            listAndMapModel.filterEntity.set(filterEntity);
            refreshData();
        });
    }


    private void initTypePopWindow() {
        //货源分类弹窗（一级）
        goodsTypePopWindow = new GoodsTypePopWindow3(getActivity());
        goodsTypePopWindow.setBgView(binding.grayLayout);
        goodsTypePopWindow.setOnResultClick((type, key2, key3) -> {
            //更换了一级，置空二级分类的选中
            binding.tvSourceType.setText("货源类型");
            setViewStateByState(binding.tvSourceType, binding.sourceTypeIv, binding.sourceTypeLayout, FILTER_UNSELECTED);
            listAndMapModel.goodsSecondType.get().setNo(DEFAULT_GOODS_TYPE);

            //处理一级的选中效果，以及一级相关的二级数据获取
            GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) type;
            listAndMapModel.goodsType.set(entity);
            int index = (int) key2;
            if (index > 0) {
                if (!TextUtils.isEmpty(entity.getName())) {
                    binding.tvGoodsClassification.setText(entity.getName());
                }
                goodsTypeNo = entity.getNo();
                goodsSecondTypeData.clear();
                goodsSecondTypeData.add(unlimitedType);
                List<GoodsInfoTypeEntity3> entity3s = goodsTypeData.get(index).getChildList();
                if (entity3s != null) {
                    goodsSecondTypeData.addAll(entity3s);
                }
            } else {
                goodsTypeNo = DEFAULT_GOODS_TYPE;
                binding.tvGoodsClassification.setText("货源分类");
                //选中不限，二级分类默认为全部一级分类下面的二级分类
                if (allSecondTypeData != null) {
                    goodsSecondTypeData.clear();
                    goodsSecondTypeData.add(unlimitedType);
                    goodsSecondTypeData.addAll(allSecondTypeData);
                }
            }
            refreshData();
        });
        goodsTypePopWindow.setOnDismissListener(() -> {
            boolean unSet = "货源分类".equals(binding.tvGoodsClassification.getText());
            if (unSet) {
                setViewStateByState(binding.tvGoodsClassification, binding.goodsClassificationIv, binding.goodsClassificationLayout, FILTER_UNSELECTED);
            } else {
                setViewStateByState(binding.tvGoodsClassification, binding.goodsClassificationIv, binding.goodsClassificationLayout, FILTER_SELECTED);
            }
        });

        //货源类型弹窗（二级）
        goodsSecondTypePopWindow = new GoodsTypePopWindow3(getActivity());
        goodsSecondTypePopWindow.setBgView(binding.grayLayout);
        goodsSecondTypePopWindow.setOnResultClick((type, key2, key3) -> {
            GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) type;
            listAndMapModel.goodsSecondType.set(entity);
            if (!TextUtils.isEmpty(entity.getName())) {
                if (entity.getName().equals("不限")) {
                    binding.tvSourceType.setText("货源类型");
                    goodsSecondTypeNo = DEFAULT_GOODS_TYPE;
                } else {
                    binding.tvSourceType.setText(entity.getName());
                    goodsSecondTypeNo = entity.getNo();
                    goodsSecondTypeNo = entity.getNo();
                }
                refreshData();
            }
        });
        goodsSecondTypePopWindow.setOnDismissListener(() -> {
            binding.flExpand.setVisibility(View.VISIBLE);
            boolean unSet = "货源类型".equals(binding.tvSourceType.getText());
            if (unSet) {
                setViewStateByState(binding.tvSourceType, binding.sourceTypeIv, binding.sourceTypeLayout, FILTER_UNSELECTED);
            } else {
                setViewStateByState(binding.tvSourceType, binding.sourceTypeIv, binding.sourceTypeLayout, FILTER_SELECTED);
            }
        });
    }

    private void initTabLayout() {
        //货物类型
        binding.tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (null == goodsTypeData || goodsTypeData.size() == 0) {
                    return;
                }
                goodsTypePopWindow.setDefItem(tab.getPosition());
                String currentGoodsType = goodsTypeData.get(tab.getPosition()).getNo();
                boolean goodsTypeIsChanged = !goodsTypeNo.equals(currentGoodsType);
                goodsTypeNo = TextUtils.isEmpty(currentGoodsType) ? "" : currentGoodsType;
                listAndMapModel.goodsType.set(goodsTypeData.get(tab.getPosition()));
                position = tab.getPosition();
                if (goodsTypeIsChanged) {
                    //当选择了货物类型后搜索内容要清空
                    resetSearchContent();
                    refreshData();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }


    private void initLoadTimePopWindow() {
        loadTimePopWindow = new LoadTimePopWindow(getActivity());
        loadTimePopWindow.setBgView(binding.grayLayout);
        loadTimePopWindow.setOnResultClick((key1, key2, key3) -> {
            //当选择了发货时间后搜索内容要清空
            resetSearchContent();
            GoodsInfoTypeEntity3 infoTypeEntity = (GoodsInfoTypeEntity3) key1;
            if (infoTypeEntity.getName().equals("明天以后")) {
                listAndMapModel.timeFilterEntity.get().setShipmentTime(infoTypeEntity.getNo());
                listAndMapModel.timeFilterEntity.get().setShipmentEndTime("");
            } else {
                listAndMapModel.timeFilterEntity.get().setShipmentTime("");
                listAndMapModel.timeFilterEntity.get().setShipmentEndTime(infoTypeEntity.getNo());
            }
            refreshData();
        });
        loadTimePopWindow.setOnDismissListener(() -> {
            binding.loadTimeIv.setSelected(false);
            binding.flExpand.setVisibility(View.VISIBLE);
            if (loadTimePopWindow.isSetLoadTime() && !loadTimePopWindow.getLoadTimeStr().equals("不限")) {
                setViewStateByState(binding.loadTime, binding.loadTimeIv, binding.loadTimeLayout, FILTER_SELECTED);
                binding.loadTime.setText(loadTimePopWindow.getLoadTimeStr());
            } else {
                binding.loadTime.setText("装货时间");
                setViewStateByState(binding.loadTime, binding.loadTimeIv, binding.loadTimeLayout, FILTER_UNSELECTED);
            }
        });
    }

    /**
     * 装货半径弹窗
     */
    private void initLoadRadiusPopWindow() {
        setViewStateByState2(binding.tvLoadingRadius, binding.loadingRadiusIv, FILTER_UNSELECTED);
        loadRadiusWindow = new LoadRadiusWindow(getActivity());
        loadRadiusWindow.setDefItem(0);
        binding.tvLoadingRadius.setText("装货地半径");
        loadRadiusWindow.setBgView(binding.grayLayout);
        loadRadiusWindow.setOnResultClick((key1, key2, key3) -> {
            //当选择了装货半径后搜索内容要清空
            resetSearchContent();
            GoodsInfoTypeEntity3 infoTypeEntity = (GoodsInfoTypeEntity3) key1;
            listAndMapModel.filterEntity.get().setRadius(Integer.parseInt(infoTypeEntity.getNo()));
            refreshData();
        });
        loadRadiusWindow.setOnDismissListener(() -> {
            binding.flExpand.setVisibility(View.VISIBLE);
            if (loadRadiusWindow.isSetRadius()) {
                if (loadRadiusWindow.getLoadRadiusStr().equals("不限")) {
                    binding.tvLoadingRadius.setText("装货地半径");
                    setViewStateByState2(binding.tvLoadingRadius, binding.loadingRadiusIv, FILTER_UNSELECTED);
                } else {
                    binding.tvLoadingRadius.setText(loadRadiusWindow.getLoadRadiusStr());
                    setViewStateByState2(binding.tvLoadingRadius, binding.loadingRadiusIv, FILTER_SELECTED);
                }
            } else {
                binding.tvLoadingRadius.setText("装货地半径");
                setViewStateByState2(binding.tvLoadingRadius, binding.loadingRadiusIv, FILTER_UNSELECTED);
            }
        });
    }

    /**
     * 初始化目的地范围选择弹窗
     */
    private void initPlaceAreaPopWindow(){
        setViewStateByState2(binding.tvDestinationArea, binding.destinationAreaIv, FILTER_UNSELECTED);
        placeAreaWindow = new PlaceAreaPopWindow(getActivity());
        placeAreaWindow.setBgView(binding.grayLayout);
        placeAreaWindow.setOnResultClick((key1, key2, key3) -> {
            //当选择了装货半径后搜索内容要清空
            resetSearchContent();
            listAndMapModel.filterEntity.get().setDestRadius(placeAreaWindow.getSelectTotalKm());
            refreshData();
        });
        placeAreaWindow.setOnDismissListener(() -> {
            if (placeAreaWindow.getSelectEchoKm02()>0) {
                binding.tvDestinationArea.setText(NumberUtil.trim0(placeAreaWindow.getSelectEchoKm02())+"公里内");
                setViewStateByState2(binding.tvDestinationArea, binding.destinationAreaIv, FILTER_SELECTED);
            } else {
                binding.tvDestinationArea.setText("选择范围");
                setViewStateByState2(binding.tvDestinationArea, binding.destinationAreaIv, FILTER_UNSELECTED);
            }
        });
    }

    private void setViewStateByState(TextView titleText, ImageView icon, LinearLayout layout, int state) {
        switch (state) {
            case FILTER_SELECTING:
                titleText.setSelected(false);
                icon.setSelected(true);
                icon.setImageResource(R.mipmap.ic_up_arrow_n);
                layout.setBackgroundResource(R.drawable.circle_gray_bkg);
                break;
            case FILTER_SELECTED:
                titleText.setSelected(true);
                icon.setSelected(false);
                icon.setImageResource(R.mipmap.ic_down_arrow);
                layout.setBackgroundResource(R.drawable.shape_theme_coner);
                break;
            case FILTER_UNSELECTED:
                titleText.setSelected(false);
                icon.setSelected(false);
                icon.setImageResource(R.mipmap.ic_down_arrow_n);
                layout.setBackgroundResource(R.drawable.circle_gray_bkg);
                break;

        }
    }


    private void setViewStateByState2(TextView titleText, ImageView icon, int state) {
        switch (state) {
            case FILTER_SELECTING:
                titleText.setSelected(false);
                icon.setSelected(true);
                icon.setImageResource(R.mipmap.ic_up_arrow_n);
                break;
            case FILTER_SELECTED:
                titleText.setSelected(true);
                icon.setSelected(false);
                icon.setImageResource(R.mipmap.ic_down_arrow);
                break;
            case FILTER_UNSELECTED:
                titleText.setSelected(false);
                icon.setSelected(false);
                icon.setImageResource(R.mipmap.ic_down_arrow_n);
                break;

        }
    }

    private void resetFilterData() {
//        resetSendLocationData();
//        resetPurposeLocationData();
//        resetRadiusSelectData();
        resetGoodsTypeSelectData();
        resetGoodsSecondTypeSelectData();
        resetTimeSelectData();
        resetFreightSortData();
        resetAllFilterData();
    }

    private void resetFreightSortData() {
        freightSortFlag = 0;
        handlerFreightSort(false);
    }

    private void resetSendLocationData() {
        if (sendGoodsLocationPopWindow3 != null) {
            initProvinceCityAreaData();
        }
        listAndMapModel.sendLocation.set(new GoodsSourceLocationEntity());
//        resetMap();
    }

    private void resetMap() {
        mIsNeedLoadByCamera = true;
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCenterLatLng, mZoom));
    }

    private void resetPurposeLocationData() {
        if (destinationPopWindow != null) {
            destinationPopWindow.resetDataAndUI();
        }
        listAndMapModel.purposeLocation.set(new GoodsSourceLocationEntity());
        setViewStateByState2(binding.tvDestination, binding.purposeGoodsIv, FILTER_UNSELECTED);
        binding.tvDestination.setText("目的地");
    }

    private void resetGoodsTypeSelectData() {
        if (goodsTypePopWindow != null) {
            goodsTypePopWindow.resetSelectItem();
        }
        goodsTypeNo = DEFAULT_GOODS_TYPE;
        listAndMapModel.goodsType.set(new GoodsInfoTypeEntity3());
        binding.tvGoodsClassification.setText("货源分类");
        setViewStateByState(binding.tvGoodsClassification, binding.goodsClassificationIv, binding.goodsClassificationLayout, FILTER_UNSELECTED);
    }

    private void resetGoodsSecondTypeSelectData() {
        if (goodsSecondTypePopWindow != null) {
            goodsSecondTypePopWindow.resetSelectItem();
        }
        goodsSecondTypeNo = DEFAULT_GOODS_TYPE;
        listAndMapModel.goodsSecondType.set(new GoodsInfoTypeEntity3());
        binding.tvSourceType.setText("货源类型");
        setViewStateByState(binding.tvSourceType, binding.sourceTypeIv, binding.sourceTypeLayout, FILTER_UNSELECTED);
    }

    private void resetTimeSelectData() {
        if (loadTimePopWindow != null) {
            loadTimePopWindow.resetSelectItem();
        }
        listAndMapModel.timeFilterEntity.set(new GoodsHallFilterEntity());

        binding.loadTime.setText("装货时间");
        setViewStateByState(binding.loadTime, binding.loadTimeIv, binding.loadTimeLayout, FILTER_UNSELECTED);
    }

    private void resetRadiusSelectData() {
        if (loadRadiusWindow != null) {
            loadRadiusWindow.resetSelectItem();
        }
        listAndMapModel.filterEntity.get().setRadius(50);
        binding.tvLoadingRadius.setText("50公里内");
        setViewStateByState2(binding.tvLoadingRadius, binding.loadingRadiusIv, FILTER_SELECTED);
    }


    private void resetMoreFilterData() {
        if (goodsMorePopWindow != null) {
            goodsMorePopWindow.resetAllFilterData();
        }
        listAndMapModel.filterEntity.set(new GoodsHallFilterEntity());
    }

    private void resetSearchContent() {
        currentIsSearching = false;
        binding.etView.setText("");
    }

    public void checkGoodsState(int position, CheckStateEntity stateEntity) {
        if (stateEntity.goodsIsGone()) {
            new RoundDialog.Builder(getActivity())
                    .title("提示")
                    .content("该货源不存在，请选择其他货源接单")
                    .singleBtn(true)
                    .confirm("知道了")
                    .confirmCallback(v -> {
                        goodsInfoAdapter.getData().remove(position);
                        goodsInfoAdapter.notifyDataSetChanged();
                    })
                    .show();
        } else if (stateEntity.goodsIsReceipted()) {
            new RoundDialog.Builder(getActivity())
                    .title("提示")
                    .content("该货源已被接单，请选择其他货源接单")
                    .singleBtn(true)
                    .confirm("知道了")
                    .confirmCallback(v -> {
                        goodsInfoAdapter.getData().remove(position);
                        goodsInfoAdapter.notifyDataSetChanged();
                    })
                    .show();

        } else {
            if (null != goodsInfoAdapter && goodsInfoAdapter.getData().size() > 0) {
                if (goodsInfoAdapter.getData().get(position).getPattern() == 1) {
                    FreightPrjDetailActivity.start(getActivity(), goodsInfoAdapter.getData().get(position).getNo(), false, false);
                } else {
                    GeneralPrjDetailActivity.start(getActivity(), goodsInfoAdapter.getData().get(position).getNo(), goodsInfoAdapter.getData().get(position).getPattern(), false);
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_ORDER_FINISH) {
            refreshData();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_LOGISTICS_REFRESH) {
            refreshListView();
        }
    }


    /**
     * 更多筛选  抽屉相关
     */
    private static final float WEIGHT_MAX_VALUE = 999.9f;
    private static final float VOLUME_MIN_VALUE = 0f;
    private static final float VOLUME_MAX_VALUE = 999.9f;
    public static final String DEFAULT_GOODS_TYPE = "Default_GoodsType";
    private WeightAndVolumeMinAndMaxAdapter weightAdapter;
    private WeightAndVolumeMinAndMaxAdapter volumeAdapter;
    private CarTypeTransportAdapter3 carTypeAdapter;
    private CarLengthTransportAdapter3 lengthAdapter;
    private String currentGoodsType = DEFAULT_GOODS_TYPE;

    private Map<String, List<GoodsInfoTypeEntity3>> carTypeNoAndCarLengthMap = new HashMap<>();
    private List<GoodsInfoTypeEntity3> allCarsTypeList = new ArrayList<>();
    private List<GoodsInfoTypeEntity3> usefulCarsTypeList = new ArrayList<>();
    private List<GoodsInfoTypeEntity3> usefulCarsLengthList = new ArrayList<>();
    private List<GoodsInfoTypeEntity3> currentTypeList = new ArrayList<>();
    private List<GoodsInfoTypeEntity3> lengthtempList = new ArrayList<>();
    private List<GoodsInfoTypeEntity3> lastCarLengthCheckedData = new ArrayList<>();
    private List<GoodsInfoTypeEntity3> lastCarTypeCheckedData = new ArrayList<>();

    //选中却不可见的车型数据
    private List<GoodsInfoTypeEntity3> invisibleCheckedCarTypes = new ArrayList<>();
    //选中却不可见的车长数据
    private List<GoodsInfoTypeEntity3> invisibleCheckedCarLength = new ArrayList<>();

    /**
     * 储存请求下来的  相应货源类型的车型车长信息，避免多次重复请求
     *
     * @param goodsTypeNo
     * @param list
     */
    public void setCarTypeAndCarLength(String goodsTypeNo, List<CarTypeAndCarLength> list) {
        if (TextUtils.isEmpty(goodsTypeNo)) {
            goodsTypeNo = DEFAULT_GOODS_TYPE;
        }
        if (!isContainCarTypeAndCarLengthByGoodsNo(goodsTypeNo)) {
            allCarTypeAndCarLengthMap.put(goodsTypeNo, list);
        }
        setCarTypeAndCarLength(list);
    }

    /**
     * 给抽屉填充数据
     *
     * @param carTypeAndCarLength
     */
    public void setCarTypeAndCarLength(List<CarTypeAndCarLength> carTypeAndCarLength) {
        if (carTypeAndCarLength == null) {
            return;
        }
        //如果要展示的货物类型和上次的货物类型不相同，就重置记录的选中数据
        if (!currentGoodsTypeIsSameWithLast(goodsTypeNo)) {
            this.currentGoodsType = goodsTypeNo;
            clearCarTypeAndCarLengthChecked();
            resetVolume();
            resetWeight();
        }
        resetCarType();
        convertToUsefulCarsTypeList(carTypeAndCarLength);
        //显示车型
        resetCarType();
        setCarTypeShowState(true);

        //显示车长
        boolean lastSelectedCarType = lastCarTypeCheckedData != null && lastCarTypeCheckedData.size() != 0;
        if (lastSelectedCarType) {
            refreshCarLengthByCarType(lastCarTypeCheckedData);
        } else {
            refreshCarLengthByCarType(usefulCarsTypeList);
        }
        binding.drawerLayout.openDrawer(Gravity.RIGHT);
    }

    private void clearCarTypeAndCarLengthChecked() {
        lastCarTypeCheckedData.clear();
        lastCarLengthCheckedData.clear();
    }

    private void convertToUsefulCarsTypeList(List<CarTypeAndCarLength> carTypeAndCarLength) {
        allCarsTypeList.clear();
        carTypeNoAndCarLengthMap.clear();
        for (CarTypeAndCarLength item : carTypeAndCarLength) {
            allCarsTypeList.add(new GoodsInfoTypeEntity3(item.getNo(), item.getName()));
            carTypeNoAndCarLengthMap.put(item.getNo(), item.getCarLenList());
        }
    }

    private void addCarLengthDefaultItem() {
        if (usefulCarsLengthList == null ||
                (usefulCarsLengthList.size() >= 1 && usefulCarsLengthList.get(0).getName().equals("不限"))) {
            return;
        }
        GoodsInfoTypeEntity3 entity3 = new GoodsInfoTypeEntity3();
        entity3.setNo(DEFAULT_GOODS_TYPE);
        entity3.setName("不限");
        usefulCarsLengthList.add(0, entity3);
    }

    private void addCarTypeDefaultItem() {
        if (usefulCarsTypeList == null ||
                (usefulCarsTypeList.size() >= 1 && usefulCarsTypeList.get(0).getName().equals("不限"))) {
            return;
        }
        GoodsInfoTypeEntity3 entity3 = new GoodsInfoTypeEntity3();
        entity3.setNo(DEFAULT_GOODS_TYPE);
        entity3.setName("不限");
        usefulCarsTypeList.add(0, entity3);
    }

    private void foldCarTypeData(boolean isFold) {
        if (null == usefulCarsTypeList) {
            return;
        }
        invisibleCheckedCarTypes.clear();
        if (isFold) {
            if (usefulCarsTypeList.size() > 9) {
                currentTypeList = usefulCarsTypeList.subList(0, 9);
                binding.carTypeMore.setImageResource(R.drawable.common_shouqi);
                //对于被选中但是却隐藏掉的数据进行保存
                if (lastCarTypeCheckedData.size() > 0) {
                    for (int i = 0; i < usefulCarsTypeList.size(); i++) {
                        for (int i1 = 0; i1 < lastCarTypeCheckedData.size(); i1++) {
                            if (lastCarTypeCheckedData.get(i1).getNo().equals(usefulCarsTypeList.get(i).getNo())) {
                                invisibleCheckedCarTypes.add(lastCarTypeCheckedData.get(i1));
                            }
                        }
                    }
                }
            } else {
                currentTypeList = usefulCarsTypeList;
                binding.carTypeMore.setImageResource(R.drawable.common_zhankai);
            }
        } else {
            currentTypeList = usefulCarsTypeList;
            binding.carTypeMore.setImageResource(R.drawable.common_zhankai);
        }
    }

    private void setCarTypeShowState(boolean isFoldCarType) {
        if (null != usefulCarsTypeList) {
            foldCarTypeData(isFoldCarType);
            carTypeAdapter.setDatas(currentTypeList);
            carTypeAdapter.resetCheckDatas();
            if (lastCarTypeCheckedData == null || lastCarTypeCheckedData.size() == 0) {
                carTypeAdapter.setCheckDefault(0);
                binding.choosedCartype.setText("");
                return;
            }

            StringBuilder lastCarTypeCheckedStr = new StringBuilder();
            if (lastCarTypeCheckedData.size() > 0) {
                for (GoodsInfoTypeEntity3 item : lastCarTypeCheckedData) {
                    if (currentTypeList.contains(item)) {
                        carTypeAdapter.setCheckDefault(currentTypeList.indexOf(item));
                    }
                    if (!TextUtils.isEmpty(item.getNo()) && !TextUtils.isEmpty(item.getNo())) {
                        lastCarTypeCheckedStr.append(item.getName());
                        lastCarTypeCheckedStr.append(",");
                    }
                }
            }

            if (lastCarTypeCheckedStr.toString().length() > 1)
                binding.choosedCartype.setText(lastCarTypeCheckedStr.substring(0, lastCarTypeCheckedStr.length() - 1));
            else {
                binding.choosedCartype.setText("");
            }
        } else {
            binding.carTypeMore.setImageResource(R.drawable.common_shouqi);
            binding.choosedCartype.setText("");
        }
    }


    private void foldCarLengthData(boolean isFold) {
        if (null == usefulCarsLengthList) {
            return;
        }
        invisibleCheckedCarLength.clear();
        if (isFold) {
            if (usefulCarsLengthList.size() > 9) {
                lengthtempList = usefulCarsLengthList.subList(0, 9);
                binding.carLengthMore.setImageResource(R.drawable.common_shouqi);
                //对于被选中但是却隐藏掉的数据进行保存
                if (lastCarLengthCheckedData.size() > 0) {
                    for (int i = 0; i < usefulCarsLengthList.size(); i++) {
                        for (int i1 = 0; i1 < lastCarLengthCheckedData.size(); i1++) {
                            if (lastCarLengthCheckedData.get(i1).getNo().equals(usefulCarsLengthList.get(i).getNo())) {
                                invisibleCheckedCarLength.add(lastCarLengthCheckedData.get(i1));
                            }
                        }
                    }
                }
            } else {
                lengthtempList = usefulCarsLengthList;
                binding.carLengthMore.setImageResource(R.drawable.common_zhankai);
            }
        } else {
            lengthtempList = usefulCarsLengthList;
            binding.carLengthMore.setImageResource(R.drawable.common_zhankai);
        }
    }

    /**
     * 展示车长筛选框信息
     *
     * @param isFold 是否折叠展示
     */
    private void setCarLengthShowState(boolean isFold) {
        if (null != usefulCarsLengthList) {
            foldCarLengthData(isFold);
            lengthAdapter.setDatas(lengthtempList);
            refreshLastCheckedLength();
            lengthAdapter.resetCheckDatas();
            if (lastCarLengthCheckedData == null || lastCarLengthCheckedData.size() == 0) {
                lengthAdapter.setCheckDefault(0);
                binding.choosedCartlen.setText("");
                return;
            }
            StringBuilder lastCarLenCheckedStr = new StringBuilder();
            if (lastCarLengthCheckedData.size() > 0) {
                for (GoodsInfoTypeEntity3 item : lastCarLengthCheckedData) {
                    if (lengthtempList.contains(item)) {
                        lengthAdapter.setCheckDefault(lengthtempList.indexOf(item));
                    }
                    if (!TextUtils.isEmpty(item.getName()) && !TextUtils.isEmpty(item.getNo())) {
                        lastCarLenCheckedStr.append(item.getName());
                        lastCarLenCheckedStr.append(",");
                    }
                }
            }
            if (TextUtils.isEmpty(lastCarLenCheckedStr.toString())) {
                binding.choosedCartlen.setText("");
                return;
            } else
                binding.choosedCartlen.setText(lastCarLenCheckedStr.substring(0, lastCarLenCheckedStr.length() - 1));
        } else {
            lengthAdapter.resetCheckDatas();
            binding.choosedCartlen.setText("");
            lastCarLengthCheckedData.clear();
        }
    }

    public void refreshCarLengthByCarType(List<GoodsInfoTypeEntity3> carTypes) {
        if (carTypes == null || carTypes.size() == 0) {
            lengthAdapter.setDatas(new ArrayList<>());
            return;
        }
        usefulCarsLengthList.clear();
        for (GoodsInfoTypeEntity3 item : carTypes) {
            List<GoodsInfoTypeEntity3> infoTypeEntity3s = carTypeNoAndCarLengthMap.get(item.getNo());
            if (infoTypeEntity3s == null || infoTypeEntity3s.size() == 0) {
                continue;
            }
            usefulCarsLengthList.addAll(infoTypeEntity3s);
        }
        usefulCarsLengthList = VehicleConstant.sortCarLength(usefulCarsLengthList);
        addCarLengthDefaultItem();
        setCarLengthShowState(true);
    }

    private void refreshLastCheckedLength() {
        //获取上次选中的车长中在当前车型中仍然有效的车长
        List<GoodsInfoTypeEntity3> usefulCheckedLength = new ArrayList<>();
        for (GoodsInfoTypeEntity3 item : lastCarLengthCheckedData) {
            if (usefulCarsLengthList.contains(item)) {
                usefulCheckedLength.add(item);
            }
        }

        lastCarLengthCheckedData.clear();
        boolean isCheckedFirstItem = lengthAdapter.getCheckDatas().size() >= 1 &&
                lengthAdapter.getCheckDatas().get(0).getName().equals("不限");
        if (isCheckedFirstItem) {
            return;
        }

        lastCarLengthCheckedData.addAll(usefulCheckedLength);
        lastCarLengthCheckedData.addAll(lengthAdapter.getCheckDatas());
        lastCarLengthCheckedData = removeDuplicate(lastCarLengthCheckedData);
    }

    private void refreshLastCheckedCarType() {
        //获取上次选中的车型中在当前货物类型中仍然有效的车型
        List<GoodsInfoTypeEntity3> usefulCheckedCarTypes = new ArrayList<>();
        for (GoodsInfoTypeEntity3 item : lastCarTypeCheckedData) {
            if (usefulCarsTypeList.contains(item)) {
                usefulCheckedCarTypes.add(item);
            }
        }

        lastCarTypeCheckedData.clear();
        boolean isCheckedFirstItem = carTypeAdapter.getCheckDatas().size() >= 1 &&
                carTypeAdapter.getCheckDatas().get(0).getName().equals("不限");
        if (isCheckedFirstItem) {
            return;
        }

        lastCarTypeCheckedData.addAll(usefulCheckedCarTypes);
        lastCarTypeCheckedData.addAll(carTypeAdapter.getCheckDatas());
        lastCarTypeCheckedData = removeDuplicate(lastCarTypeCheckedData);
    }

    private void removeDuplicateCarLength() {
        usefulCarsLengthList.removeAll(Collections.singleton(null));
        LinkedHashSet<GoodsInfoTypeEntity3> set = new LinkedHashSet<>();
        set.addAll(usefulCarsLengthList);
        usefulCarsLengthList = new ArrayList<>(set);
    }

    private List<GoodsInfoTypeEntity3> removeDuplicate(List<GoodsInfoTypeEntity3> list) {
        if (list == null || list.size() == 0) return new ArrayList<>();
        list.removeAll(Collections.singleton(null));
        LinkedHashSet<GoodsInfoTypeEntity3> set = new LinkedHashSet<>();
        set.addAll(list);
        return new ArrayList<>(set);
    }

    /**
     * 初始化车型选择相关控件
     */
    private void initCarTypeView() {
        carTypeAdapter = new CarTypeTransportAdapter3(mContext, null);
        binding.goodsCarTypeList.setLayoutManager(new GridLayoutManager(mContext, 3));
        binding.goodsCarTypeList.setAdapter(carTypeAdapter);
        carTypeAdapter.setMultiSelect(true);
        carTypeAdapter.setLimit(true);
        carTypeAdapter.setOnItemMultiClick((goodsInfoTypeEntity3s, position) -> {
            lastCarTypeCheckedData.clear();
            if (goodsInfoTypeEntity3s != null && goodsInfoTypeEntity3s.size() > 0)
                lastCarTypeCheckedData.addAll(goodsInfoTypeEntity3s);
            if (invisibleCheckedCarTypes.size() > 0)
                lastCarTypeCheckedData.addAll(invisibleCheckedCarTypes);
            showCheckedCarType();
            //没有选中任何车型（包括不限），车长显示为空
            if (lastCarTypeCheckedData.size() == 0) {
                refreshCarLengthByCarType(null);
                return;
            }

            if (goodsInfoTypeEntity3s != null && goodsInfoTypeEntity3s.size() > 0) {
                if (goodsInfoTypeEntity3s.get(0).getName().equals("不限")) {//选中不限
                    refreshCarLengthByCarType(allCarsTypeList);
                    return;
                }
            }
            //选中的有效车型
            refreshCarLengthByCarType(lastCarTypeCheckedData);
        });
    }


    /**
     * 车长选择显示处理
     */
    private void showCheckedCarLen() {
        if ((lengthAdapter.getCheckDatas() == null || lengthAdapter.getCheckDatas().size() < 1) && invisibleCheckedCarLength.size() < 1) {////没有选中任何可见选项并且也没有隐藏的选中项
            binding.choosedCartlen.setText("");
        } else if (lengthAdapter.getCheckDatas() != null && lengthAdapter.getCheckDatas().size() > 0
                && lengthAdapter.getCheckDatas().get(0).getName().equals("不限")) {//选中了不限
            binding.choosedCartlen.setText("");
        } else {//选中了“不限”以外的选项
            if (lastCarLengthCheckedData.size() > 0) {
                VehicleConstant.sortCarLength(lastCarLengthCheckedData);
                StringBuilder carLenCheckedStr = new StringBuilder();
                for (GoodsInfoTypeEntity3 item : lastCarLengthCheckedData) {
                    carLenCheckedStr.append(item.getName());
                    carLenCheckedStr.append(",");
                }
                binding.choosedCartlen.setText(carLenCheckedStr.substring(0, carLenCheckedStr.length() - 1));
            } else {
                binding.choosedCartlen.setText("");
            }
        }
    }

    /**
     * 车型选择显示处理
     */
    private void showCheckedCarType() {
        if ((carTypeAdapter.getCheckDatas() == null || carTypeAdapter.getCheckDatas().size() < 1) && invisibleCheckedCarTypes.size() < 1) {//没有选中任何可见选项并且也没有隐藏的选中项
            binding.choosedCartype.setText("");
            binding.choosedCartlen.setText("");
        } else if (carTypeAdapter.getCheckDatas() != null && carTypeAdapter.getCheckDatas().size() > 0
                && carTypeAdapter.getCheckDatas().get(0).getName().equals("不限")) {//选中了不限
            binding.choosedCartype.setText("");
            lastCarTypeCheckedData.clear();
            lastCarTypeCheckedData.add(carTypeAdapter.getCheckDatas().get(0));
        } else {//选中了“不限”以外的选项
            if (lastCarTypeCheckedData.size() > 0) {
                StringBuilder carTypeCheckedStr = new StringBuilder();
                for (GoodsInfoTypeEntity3 item : lastCarTypeCheckedData) {
                    carTypeCheckedStr.append(item.getName());
                    carTypeCheckedStr.append(",");
                }
                binding.choosedCartype.setText(carTypeCheckedStr.substring(0, carTypeCheckedStr.length() - 1));
            } else {
                binding.choosedCartype.setText("");
            }
        }
    }

    /**
     * 初始化车长选择相关控件
     */
    private void initCarLengthView() {
        lengthAdapter = new CarLengthTransportAdapter3(mContext, null);
        binding.goodsCarLengthList.setLayoutManager(new GridLayoutManager(mContext, 3));
        binding.goodsCarLengthList.setAdapter(lengthAdapter);
        lengthAdapter.setMultiSelect(true);
        lengthAdapter.setLimit(true);
        lengthAdapter.setDefItem(-1);
        lengthAdapter.setOnItemMultiClick((goodsInfoTypeEntity3s, position) -> {
            lastCarLengthCheckedData.clear();
            //有选中项则添加
            if (goodsInfoTypeEntity3s != null && goodsInfoTypeEntity3s.size() > 0)
                lastCarLengthCheckedData.addAll(goodsInfoTypeEntity3s);
            //有隐藏选种项则添加
            if (invisibleCheckedCarLength.size() > 0)
                lastCarTypeCheckedData.addAll(invisibleCheckedCarLength);
            showCheckedCarLen();
        });
    }

    public void resetAllFilterData() {
        carTypeAdapter.resetCheckDatas();
        carTypeAdapter.setDefItem(-1);
        lengthAdapter.resetCheckDatas();
        lengthAdapter.setDefItem(-1);
        lastCarLengthCheckedData.clear();
        lastCarTypeCheckedData.clear();
        resetCarTypeAndCarLength();
        resetVolume();
        resetWeight();

        listAndMapModel.filterEntity.get().setLengthType(null);
        listAndMapModel.filterEntity.get().setCarType(null);
    }

    private void resetCarTypeAndCarLength() {
        resetCarType();
        refreshCarLengthByCarType(usefulCarsTypeList);
        setCarTypeShowState(true);
    }

    private void resetCarType() {
        resetCarType(true);
    }

    private void resetCarType(boolean isAddDefaultItem) {
        usefulCarsTypeList = allCarsTypeList;
        if (isAddDefaultItem) {
            addCarTypeDefaultItem();
        }
    }

    private void initVolumeRecyclerView() {
        List<WeightAndVolumeEntity> datas = new ArrayList<>();
        datas.add(new WeightAndVolumeEntity(0, 10));
        datas.add(new WeightAndVolumeEntity(10, 20));
        datas.add(new WeightAndVolumeEntity(20, 30));
        datas.add(new WeightAndVolumeEntity(30, 40));
        datas.add(new WeightAndVolumeEntity(40, 50));
        datas.add(new WeightAndVolumeEntity(50, VOLUME_MAX_VALUE));
        volumeAdapter = new WeightAndVolumeMinAndMaxAdapter(mContext, datas);
        volumeAdapter.setMultiSelect(false);
        volumeAdapter.setItemSelect(true);
        volumeAdapter.setDefItem(-1);
        volumeAdapter.setOnItemClick(new TransportAdapterOnItemClick<WeightAndVolumeEntity>() {
            @Override
            public void onItemClick(WeightAndVolumeEntity weightAndVolumeEntity, int position) {
                if (!weightAndVolumeEntity.isSelect() && datas.size() >= position + 1) {
                    for (int i = 0; i < datas.size(); i++) {
                        if (i == position) {
                            datas.get(i).setSelect(true);
                        } else {
                            datas.get(i).setSelect(false);
                        }
                    }
                    listAndMapModel.filterEntity.get().setVolume(weightAndVolumeEntity.getMin());
                    listAndMapModel.filterEntity.get().setMaxVolume(weightAndVolumeEntity.getMax());
                    binding.choosedVolume.setText(weightAndVolumeEntity.toString());
                } else {
                    datas.get(position).setSelect(false);
                    resetVolume();
                }
                volumeAdapter.notifyDataSetChanged();
            }
        });
        binding.volumeRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 4));
        binding.volumeRecyclerView.setAdapter(volumeAdapter);
    }

    private void initWeightRecyclerView() {
        List<WeightAndVolumeEntity> datas = new ArrayList<>();
        datas.add(new WeightAndVolumeEntity(0, 5));
        datas.add(new WeightAndVolumeEntity(5, 10));
        datas.add(new WeightAndVolumeEntity(10, 15));
        datas.add(new WeightAndVolumeEntity(15, 20));
        datas.add(new WeightAndVolumeEntity(20, WEIGHT_MAX_VALUE));
        weightAdapter = new WeightAndVolumeMinAndMaxAdapter(mContext, datas);
        weightAdapter.setMultiSelect(false);
        weightAdapter.setItemSelect(true);
        weightAdapter.setDefItem(-1);
        weightAdapter.setOnItemClick(new TransportAdapterOnItemClick<WeightAndVolumeEntity>() {
            @Override
            public void onItemClick(WeightAndVolumeEntity weightAndVolumeEntity, int position) {
                if (!weightAndVolumeEntity.isSelect() && datas.size() >= position + 1) {
                    for (int i = 0; i < datas.size(); i++) {
                        if (i == position) {
                            datas.get(i).setSelect(true);
                        } else {
                            datas.get(i).setSelect(false);
                        }
                    }
                    listAndMapModel.filterEntity.get().setMinWeight(String.valueOf(weightAndVolumeEntity.getMin()));
                    listAndMapModel.filterEntity.get().setMaxWeight(String.valueOf(weightAndVolumeEntity.getMax()));
                    binding.choosedWieght.setText(weightAndVolumeEntity.toString());
                } else {
                    datas.get(position).setSelect(false);
                    resetWeight();
                }
                weightAdapter.notifyDataSetChanged();
            }
        });
        binding.weightRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 4));
        binding.weightRecyclerView.setAdapter(weightAdapter);
    }


    private void resetWeight() {
        binding.choosedWieght.setText("");
        weightAdapter.resetCheckDatas();
        weightAdapter.setDefItem(-1);
        listAndMapModel.filterEntity.get().setMaxWeight(null);
        listAndMapModel.filterEntity.get().setMinWeight(null);
    }

    private void resetVolume() {
        binding.choosedVolume.setText("");
        volumeAdapter.resetCheckDatas();
        volumeAdapter.setDefItem(-1);
        listAndMapModel.filterEntity.get().setVolume(VOLUME_MIN_VALUE);
        listAndMapModel.filterEntity.get().setMaxVolume(VOLUME_MIN_VALUE);
    }

    public boolean isChooseFirstDefaultItem(List<GoodsInfoTypeEntity3> list) {
        if (list != null && list.size() >= 1) {
            return list.get(0).getName().equals("不限");
        }
        return false;
    }

    private boolean currentGoodsTypeIsSameWithLast(String goodsType) {
        if (TextUtils.isEmpty(goodsType)) return false;
        return goodsType.equals(currentGoodsType);
    }

    private void setFilterBtnStatus() {
        boolean hasFilter = false;
        if (!isChooseFirstDefaultItem(carTypeAdapter.getCheckDatas())) {
            hasFilter = true;
        }
        if (!isChooseFirstDefaultItem(lengthAdapter.getCheckDatas())) {
            hasFilter = true;
        }
        if (!(listAndMapModel.filterEntity.get().getVolume() == VOLUME_MIN_VALUE &&
                listAndMapModel.filterEntity.get().getMaxVolume() == VOLUME_MAX_VALUE)) {
            hasFilter = true;
        }
        if (!(listAndMapModel.filterEntity.get().getMinWeight() == null &&
                listAndMapModel.filterEntity.get().getMaxWeight() == null)) {
            hasFilter = true;
        }
        //设置选中颜色
        if (hasFilter) {
            binding.tvMore.setTextColor(ContextCompat.getColor(mContext, R.color.color_main));
        } else {
            binding.tvMore.setTextColor(ContextCompat.getColor(mContext, R.color.color_333333));
        }
    }
}